package com.robot.controller;

import cn.hutool.json.JSONObject;
import com.robot.common.result.Response;
import com.robot.common.utils.RedBookSignatureUtil;
import com.robot.dao.dto.IDDTO;
import com.robot.dao.dto.SendMessageDTO;
import com.robot.dao.vo.ChatVO;
import com.robot.service.ChatService;
import com.robot.service.RobotUserUsetimeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;
import redbook.RedBookCaller;

import java.io.Serializable;
import java.util.UUID;

@RestController
@RequestMapping("/chat")
@Slf4j
@Api(tags = "对话相关接口")
public class ChatController {
    @Autowired
    private ChatService chatService;
    @Autowired
    private RobotUserUsetimeService robotUserUsetimeService;
    @PostMapping("/queryChat")
    @ApiOperation(value = "根据ID查询对话")
    public Response<ChatVO> queryChatByUserIdAndRobotId(@RequestBody IDDTO iddto) {
        ChatVO chatVO = chatService.query(iddto);
        return Response.success(chatVO);
    }

    @PostMapping(value = "/sendMessage", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @ApiOperation("发送对话")
    public Flux<String> sendMessage(@RequestParam(value = "robotId") String robotId,
                                    @RequestParam(value = "userId") String userId,
                                    @RequestParam(value = "message") String message,
                                    @RequestParam(value = "messageType",required = false) Integer messageType,
                                    @RequestParam(value = "file",required = false) MultipartFile file
    ) throws Exception {
        SendMessageDTO sendMessageDTO=new SendMessageDTO();
        sendMessageDTO.setRobotId(robotId);
        sendMessageDTO.setUserId(userId);
        sendMessageDTO.setMessage(message);
        sendMessageDTO.setMessageType(messageType);
        robotUserUsetimeService.creatrobotuser(sendMessageDTO.getRobotId(),sendMessageDTO.getUserId());
        return chatService.sendChat(sendMessageDTO,file);
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class SendImageChatResp implements Serializable {
        String image;
    }
    @PostMapping(value = "/sendImageChat")
    @ApiOperation("图生图")
    // 直接对接工作流的图生图接口
    public Response<SendImageChatResp> sendImageChat(@RequestParam(value = "file",required = false) MultipartFile file
    ) throws Exception {
        SendImageChatResp tempData=new SendImageChatResp(chatService.sendImageChat(file));
//        SendImageChatResp tempData=new SendImageChatResp("testttttt");
//        String res=chatService.sendImageChat(file);

        return Response.success(tempData);
    }


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class GetSignFromRedBook implements Serializable {
        String appKey;
        String nonce;
        String timestamp;
        String signature;
    }

    @PostMapping(value = "/getSignFromRedBook")
    @ApiOperation("去小红书拿鉴权的签名")
    // 直接对接工作流的图生图接口。接口文档：https://agora.xiaohongshu.com/doc/js
    public Response<GetSignFromRedBook> getSignFromRedBook(
    ) throws Exception {
//        SendImageChatResp tempData=new SendImageChatResp(chatService.sendImageChat(file));
//        SendImageChatResp tempData=new SendImageChatResp("testttttt");
//        String res=chatService.sendImageChat(file);
        //step 1

        String nonce="exampleNonce";
        // UUID.randomUUID().toString().replace("-", "").substring(0, 10);
        long timestamp = System.currentTimeMillis();
        String appKey="red.8KozpCRLB9jToQWO";
//        String appKey="red.zfpSuG60pxEZeZJd";

        String accessTokenHttpRes= RedBookCaller.getAccessToken(nonce,timestamp,appKey);
// accessToken.data.access_token
        JSONObject jsonObjectTemp1 = new JSONObject(accessTokenHttpRes);
        JSONObject jsonObjectTemp2= jsonObjectTemp1.getJSONObject("data");
        String accessToken= jsonObjectTemp2.getStr("access_token");
        String signature= RedBookSignatureUtil.buildSignature(nonce,""+timestamp,accessToken,appKey);

        GetSignFromRedBook res=new GetSignFromRedBook();
        res.setNonce(nonce);
        res.setAppKey(appKey);
        res.setTimestamp(""+timestamp);
        res.setSignature(signature);
        return Response.success(res);
    }
}
